package com.hulk.dryad.manage.security.listener;

import cn.hutool.core.collection.CollUtil;
import com.hulk.dryad.manage.security.handler.AuthenticationSuccessEventHandler;
import lombok.RequiredArgsConstructor;
import net.dreamlu.mica.auto.annotation.AutoListener;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * @author hulk
 * @date 2020/03/25 认证成功事件监听器
 */
@Component
@AutoListener
@RequiredArgsConstructor
public class AuthenticationSuccessEventListener implements ApplicationListener<AuthenticationSuccessEvent> {

	private final ObjectProvider<AuthenticationSuccessEventHandler> dryadAuthenticationSuccessEventHandler;

	/**
	 * Handle an application event.
	 * @param event the event to respond to
	 */
	@Override
	public void onApplicationEvent(AuthenticationSuccessEvent event) {
		AuthenticationSuccessEventHandler 	handler  =dryadAuthenticationSuccessEventHandler.getIfAvailable();
		Authentication authentication = (Authentication) event.getSource();
		if (handler != null && isUserAuthentication(authentication)) {
			ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder
					.getRequestAttributes();
			HttpServletRequest request = requestAttributes.getRequest();
			HttpServletResponse response = requestAttributes.getResponse();
			handler.handle(authentication, request, response);
		}
	}


	private boolean isUserAuthentication(Authentication authentication) {
		return authentication.getPrincipal() instanceof User
				|| CollUtil.isNotEmpty(authentication.getAuthorities());
	}

}
